<template>
	<div class="seckill-detail">
		<!-- 顶部 banner -->
		<div class="seckill-banner">
			<img src="/static/seckill-banner.jpg" alt="秒杀 banner" class="banner-img">
		</div>
		<!-- 场次切换导航 -->
		<div class="seckill-tabs">
			<div v-for="(tab, index) in tabs" :key="index" :class="['tab-item', { active: currentTab === index }]"
				@click="switchTab(index)">
				<span class="tab-time">{{ tab.seckillBatch }}</span>
				<span class="tab-status" :class="{ 
          ongoing: tab.status === '进行中', 
          notStart: tab.status === '未开始',
          ended: tab.status === '已结束' 
        }">
					{{ tab.status }}
				</span>
			</div>
		</div>
		<!-- 倒计时区域 -->
		<div class="countdown" v-if="showCountdown">
			<span class="countdown-label">{{ countdownLabel }}</span>
			<span class="countdown-box" v-for="(item, idx) in countdownTime" :key="idx">
				{{ item }}
			</span>
		</div>
		<!-- 商品列表 -->
		<div class="goods-list">
			<div class="goods-item" v-for="(goods, goodsIdx) in currentGoodsList" :key="goodsIdx"
				v-if="currentGoodsList.length > 0">
				<img :src="goods.picUrl" alt="商品图" @click="navToDetailPage1(goods)" class="goods-img">
				<div class="goods-info" @click="navToDetailPage1(goods)">
					<p class="goods-name">{{ goods.name }}</p>
					<p class="goods-price">
						秒杀价 ¥{{ goods.retailPrice }}
						<span class="original-price">原价 ¥{{ goods.counterPrice }}</span>
					</p>
					<div class="stock" v-if="goods.stock === 0">仅剩0件</div>
					<button class="buy-btn" :disabled="!canBuy" >
						{{ buyButtonText }}
					</button>
				</div>
			</div>
			<div class="empty-tip" v-else>当前场次暂无商品</div>
		</div>
	</div>
</template>

<script>
	import Vue from 'vue';

	import {
		getSeckillBathGodosList
	} from '@/config/api/seckillBatch.js';

	export default {
		data() {
			return {
				tabs: [{
						seckillBatch: '00:00',
						status: '未开始',
						dtsGoodsList: [{
							picUrl: '/static/goods1.png',
							name: '雪纺衬衫2020秋季新款喇叭袖设计感绿色衬衣小雏菊碎花上衣',
							seckillPrice: 99,
							originalPrice: 106.26,
							stock: 0
						}]
					},
					{
						seckillBatch: '10:00',
						status: '未开始',
						dtsGoodsList: [{
							picUrl: '/static/goods2.png',
							name: '商品2名称',
							seckillPrice: 88,
							originalPrice: 120,
							stock: 10
						}]
					},
					{
						seckillBatch: '12:00',
						status: '未开始',
						dtsGoodsList: [{
							picUrl: '/static/goods3.png',
							name: '商品3名称',
							seckillPrice: 77,
							originalPrice: 110,
							stock: 8
						}]
					},
					{
						seckillBatch: '18:00',
						status: '未开始',
						dtsGoodsList: [{
							picUrl: '/static/goods4.png',
							name: '商品4名称',
							seckillPrice: 66,
							originalPrice: 100,
							stock: 15
						}]
					},
				],
				seckillBatchGoodsList: [],
				currentTab: 0, // 当前选中场次索引
				countdownTimer: null, // 倒计时定时器
				countdownTime: ['00', '00', '00'], // 时、分、秒
				countdownLabel: '距结束还剩', // 倒计时标签
				showCountdown: true, // 是否显示倒计时
				currentTabStatus: '未开始', // 当前场次状态
				nextSession: null, // 下一场次数据
			};
		},
		onLoad() {
			this.loadData();
		},
		computed: {
			currentGoodsList() {
				return this.tabs[this.currentTab]?.dtsGoodsList;
			},
			canBuy() {
				return (
					this.currentTabStatus === '进行中'
					// this.currentGoodsList.some(goods => goods.stock > 0)
				);
			},
			buyButtonText() {
				if (this.currentTabStatus === '未开始') return '未开始';
				const allStockZero = this.currentGoodsList.every(goods => goods.stock === 0);
				if (allStockZero) return '已抢光';
				return '马上抢';
			}
		},
		mounted() {
			this.initCurrentSession(); // 初始化当前应该显示的场次
			this.updateAllTabsStatus(); // 更新所有场次状态
			this.initCountdown(); // 初始化倒计时
		},
		beforeDestroy() {
			this.clearTimer(); // 组件销毁前清除定时器
		},
		methods: {
			async loadData() {
				try { // 秒杀商品
					const res = await getSeckillBathGodosList()
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.tabs = res.data.data
						// console.log(JSON.stringify(this.tabs, null, 2));
						// console.log(JSON.stringify(this.seckillBatchGoodsList, null, 2));
						// console.log(this.carouselList);
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			},
			// 初始化当前应该显示的场次（核心逻辑）
			initCurrentSession() {
				const now = new Date();
				const currentTime = now.getTime();
				const tabCount = this.tabs.length;
				// 查找当前进行中的场次
				for (let i = 0; i < tabCount; i++) {
					const tab = this.tabs[i];
					const startTime = this.parseTime(tab.seckillBatch);
					const endTime = this.parseTime(this.getNextTab(i).seckillBatch);
					if (currentTime >= startTime && currentTime < endTime) {
						this.currentTab = i;
						this.currentTabStatus = '进行中';
						return;
					}
				}
				// 如果没有进行中的场次，找到最近的未开始场次
				for (let i = 0; i < tabCount; i++) {
					const tab = this.tabs[i];
					const startTime = this.parseTime(tab.seckillBatch);
					const endTime = this.parseTime(this.getNextTab(i).seckillBatch);
					if (currentTime < startTime) {
						this.currentTab = i;
						this.currentTabStatus = '未开始';
						return;
					}
				}
				// 如果所有场次都已结束，默认显示第一个场次
				this.currentTab = 0;
				this.currentTabStatus = '已结束';
			},
			// 获取下一个场次，最后一个场次的下一个场次是第一个场次
			getNextTab(index) {
				const tabCount = this.tabs.length;
				return this.tabs[(index + 1) % tabCount];
			},
			// 更新所有场次状态
			updateAllTabsStatus() {
				const now = new Date();
				const currentTime = now.getTime();
				const tabCount = this.tabs.length;
				this.tabs.forEach((tab, index) => {
					const startTime = this.parseTime(tab.seckillBatch);
					const endTime = this.parseTime(this.getNextTab(index).seckillBatch);
					if (currentTime >= startTime && currentTime < endTime) {
						tab.status = '进行中';
					} else if (currentTime < startTime) {
						tab.status = '未开始';
					} else {
						tab.status = '已结束';
					}
				});
			},
			// 切换场次
			switchTab(index) {
				this.currentTab = index;
				this.updateCurrentTabStatus();
				this.initCountdown();
			},
			// 更新当前选中场次的状态
			updateCurrentTabStatus() {
				const now = new Date();
				const currentTime = now.getTime();
				const tab = this.tabs[this.currentTab];
				const nextTab = this.getNextTab(this.currentTab);
				const startTime = this.parseTime(tab.seckillBatch);
				const endTime = this.parseTime(nextTab.seckillBatch);
				if (currentTime >= startTime && currentTime < endTime) {
					tab.status = '进行中';
					this.currentTabStatus = '进行中';
					this.countdownLabel = '距结束还剩';
					this.nextSession = null;
				} else if (currentTime < startTime) {
					tab.status = '未开始';
					this.currentTabStatus = '未开始';
					this.countdownLabel = '距开始还剩';
					this.nextSession = null;
				} else {
					tab.status = '已结束';
					this.currentTabStatus = '已结束';
					this.nextSession = this.findNextSession();
					if (this.nextSession) {
						this.countdownLabel = `距${this.nextSession.seckillBatch}场开始还剩`;
					} else {
						this.countdownLabel = '今日场次已结束';
						this.showCountdown = false;
					}
				}
			},
			// 查找下一个未开始的场次
			findNextSession() {
				const now = new Date();
				const currentTime = now.getTime();
				const tabCount = this.tabs.length;
				for (let i = 0; i < tabCount; i++) {
					const tab = this.tabs[i];
					const startTime = this.parseTime(tab.seckillBatch);
					if (currentTime < startTime) {
						return tab;
					}
				}
				// 如果今天所有场次都已结束，返回明天的第一个场次
				if (tabCount > 0) {
					return {
						...this.tabs[0],
						startTime: this.getTomorrowTime(this.tabs[0].seckillBatch)
					};
				}
				return null;
			},
			// 获取明天的时间戳
			getTomorrowTime(timeStr) {
				const [hours, minutes] = timeStr.split(':').map(Number);
				const now = new Date();
				now.setDate(now.getDate() + 1); // 加一天
				return new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes, 0).getTime();
			},
			// 初始化倒计时
			initCountdown() {
				this.clearTimer();
				const now = new Date();
				const currentTime = now.getTime();
				const tab = this.tabs[this.currentTab];
				const nextTab = this.getNextTab(this.currentTab);
				let targetTime;
				if (this.currentTabStatus === '进行中') {
					// 进行中，倒计时到结束时间（下一场开始时间）
					targetTime = this.parseTime(nextTab.seckillBatch);
				} else if (this.currentTabStatus === '未开始') {
					// 未开始，倒计时到开始时间
					targetTime = this.parseTime(tab.seckillBatch);
				} else if (this.currentTabStatus === '已结束' && this.nextSession) {
					// 已结束，倒计时到下一场开始
					const nextStartTime = this.parseTime(this.nextSession.seckillBatch);
					targetTime = nextStartTime < currentTime ? this.getTomorrowTime(this.nextSession.seckillBatch) :
						nextStartTime;
				} else {
					// 没有下一场，隐藏倒计时
					this.showCountdown = false;
					return;
				}
				this.showCountdown = true;
				// 更新倒计时的函数
				const updateCountdown = () => {
					const now = new Date();
					const diff = targetTime - now.getTime();
					if (diff <= 0) {
						// 时间到，重新初始化
						this.updateAllTabsStatus();
						this.initCurrentSession();
						this.initCountdown();
						return;
					}
					const hours = Math.floor(diff / (1000 * 3600));
					const minutes = Math.floor((diff % (1000 * 3600)) / (1000 * 60));
					const seconds = Math.floor((diff % (1000 * 60)) / 1000);
					this.countdownTime = [
						hours.toString().padStart(2, '0'),
						minutes.toString().padStart(2, '0'),
						seconds.toString().padStart(2, '0')
					];
				};
				// 立即执行一次
				updateCountdown();
				// 每秒更新一次
				this.countdownTimer = setInterval(updateCountdown, 1000);
			},
			// 清除定时器
			clearTimer() {
				if (this.countdownTimer) {
					clearInterval(this.countdownTimer);
					this.countdownTimer = null;
				}
			},
			// 解析时间字符串为时间戳
			parseTime(timeStr) {
				const [hours, minutes] = timeStr.split(':').map(Number);
				const now = new Date();
				return new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes, 0).getTime();
			},
			// 处理购买逻辑
			handleBuy(goods) {
				if (this.canBuy) {
					goods.stock--;
					Vue.prototype.$toast('抢购成功');
				} else if (this.currentTabStatus === '未开始') {
					Vue.prototype.$toast('场次未开始');
				} else {
					Vue.prototype.$toast('商品已抢光');
				}
			},
			navToDetailPage1(item) {
				// 获取当前场次数据
				const currentTabData = this.tabs[this.currentTab];
				// 当前场次开始时间
				const startTime = currentTabData.seckillBatch;
				// 获取下一场次数据，用于确定当前场次结束时间
				const nextTabData = this.getNextTab(this.currentTab);
				// 当前场次结束时间（下一场开始时间）
				const endTime = nextTabData.seckillBatch;

				let id = item.id;
				uni.navigateTo({
					// 拼接时间参数传递给目标页面
					url: `/pages/product/product?goodsId=${id}&seckillBatch=${startTime}&endTime=${endTime}`
				});
			},
		}
	};
</script>

<style>
	.seckill-detail {
		background-color: #fff;
	}

	.seckill-banner {
		width: 100%;
		height: 180px;
	}

	.banner-img {
		width: 100%;
		display: block;
		height: 180px;
	}

	.seckill-tabs {
		display: flex;
		border-bottom: 1px solid #f4f4f4;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 10px 0;
		cursor: pointer;
	}

	.tab-item.active {
		color: #ff0000;
		border-bottom: 2px solid #ff0000;
	}

	.tab-time {
		display: block;
		font-size: 14px;
	}

	.tab-status {
		font-size: 12px;
	}

	.tab-status.ongoing {
		color: #ff0000;
	}

	.tab-status.notStart {
		color: #999;
	}

	.tab-status.ended {
		color: #999;
		text-decoration: line-through;
	}

	.countdown {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 10px 0;
	}

	.countdown-label {
		margin-right: 5px;
		font-size: 14px;
	}

	.countdown-box {
		display: inline-block;
		width: 28px;
		height: 28px;
		line-height: 28px;
		text-align: center;
		background-color: #ff0000;
		color: #fff;
		border-radius: 4px;
		margin: 0 2px;
		font-size: 14px;
	}

	.goods-list {
		padding: 10px;
	}

	.goods-item {
		display: flex;
		margin-bottom: 10px;
		border: 1px solid #f4f4f4;
		border-radius: 4px;
		padding: 10px;
	}

	.goods-img {
		width: 100px;
		height: 100px;
		margin-right: 10px;
	}

	.goods-info {
		flex: 1;
	}

	.goods-name {
		font-size: 14px;
		line-height: 1.4;
		margin-bottom: 5px;
	}

	.goods-price {
		font-size: 14px;
		color: #ff0000;
		margin-bottom: 5px;
	}

	.original-price {
		color: #999;
		text-decoration: line-through;
		margin-left: 5px;
	}

	.stock {
		color: #ff0000;
		font-size: 12px;
		margin-bottom: 5px;
	}

	.buy-btn {
		background-color: #ff0000;
		color: #fff;
		border: none;
		padding: 6px 12px;
		border-radius: 4px;
		cursor: pointer;
	}

	.buy-btn:disabled {
		background-color: #999;
		cursor: not-allowed;
	}

	.buy-btn:not(:disabled) {
		background-color: #ff0000;
		cursor: pointer;
	}
</style>